<template>
  <div class="publish-container">
    <div class="header">
      <div class="back-button" @click="$router.go(-1)">
        ←
      </div>
      <h1>发布视频</h1>
      <div></div>
    </div>

    <div class="upload-area">
      <div class="form-container">
        <div class="form-group">
          <label>视频标题</label>
          <input 
            v-model="form.title" 
            placeholder="请输入视频标题" 
            class="input-field" 
            maxlength="30"
            @keydown.enter="submitForm"
          />
          <div class="input-counter">{{ form.title.length }}/30</div>
        </div>

        <div class="form-group">
          <label>选择视频</label>
          <div class="upload-wrapper">
            <input type="file" accept="video/mp4,video/quicktime" @change="handleFileSelect" ref="fileInput" style="display: none" />
            <div v-if="videoUrl" class="video-preview-container">
              <video :src="videoUrl" class="video-preview" controls></video>
              <button @click="removeVideo" class="remove-btn">✕</button>
            </div>
            <div v-else class="upload-placeholder" @click="$refs.fileInput.click()">
              <div class="upload-icon">📹</div>
              <div class="upload-tip">点击上传视频</div>
              <div class="upload-desc">支持MP4格式，最大100MB</div>
              <div class="upload-drag-tip">或拖拽视频到此处</div>
            </div>
          </div>
        </div>

        <button 
          @click="submitForm" 
          :disabled="!canSubmit" 
          :class="['submit-btn', { loading: uploading }]"
        >
          <span v-if="uploading" class="loading-spinner">⏳</span>
          {{ uploading ? '上传中...' : '发布视频' }}
        </button>

        <div class="tips">
          <div class="tip-title">发布提示：</div>
          <ul class="tip-list">
            <li>请确保您拥有视频的版权或授权</li>
            <li>不得上传色情、暴力、侵权等内容</li>
            <li>视频上传后将进行内容审核</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="upload-progress" v-if="uploading">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
      </div>
      <div class="progress-text">{{ uploadProgress }}%</div>
      <div class="progress-tip">视频上传中，请勿关闭页面...</div>
    </div>

        <!-- 底部导航 -->
    <div class="bottom-nav">
      <div class="nav-item active" @click="goToFeed">
        <span class="nav-icon">🏠</span>
        <span class="nav-text">首页</span>
      </div>
      <div class="nav-item" @click="goToPublish">
        <span class="nav-icon">➕</span>
        <span class="nav-text">发布</span>
      </div>
      <div class="nav-item" @click="goToLog">
        <span class="nav-icon">📜</span>
        <span class="nav-text">日志</span>
      </div>
      <div class="nav-item" @click="goToProfile">
        <span class="nav-icon">👤</span>
        <span class="nav-text">我的</span>
      </div>

    </div>
  </div>
</template>

<script>
import API from '@/services/api'

export default {
  name: 'Publish',
  data() {
    return {
      form: {
        title: ''
      },
      videoFile: null,
      videoUrl: '',
      uploading: false,
      uploadProgress: 0
    }
  },
  computed: {
    canSubmit() {
      return this.form.title.trim() && this.videoFile && !this.uploading
    }
  },
  created() {
    if (!this.$store.getters.isLoggedIn) {
      this.$message.warning('请先登录')
      this.$router.push('/login')
    }
    
    // 添加拖拽上传事件监听
    this.setupDragAndDrop()
  },
  mounted() {
    // 页面关闭前提示
    window.addEventListener('beforeunload', this.handleBeforeUnload)
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('beforeunload', this.handleBeforeUnload)
    this.removeDragAndDrop()
    
    // 释放内存
    if (this.videoUrl) {
      URL.revokeObjectURL(this.videoUrl)
    }
  },
  methods: {
    setupDragAndDrop() {
      window.addEventListener('dragover', this.handleDragOver)
      window.addEventListener('drop', this.handleDrop)
    },
    
    removeDragAndDrop() {
      window.removeEventListener('dragover', this.handleDragOver)
      window.removeEventListener('drop', this.handleDrop)
    },
    
    handleDragOver(e) {
      e.preventDefault()
    },
    
    handleDrop(e) {
      e.preventDefault()
      if (!e.dataTransfer.files || e.dataTransfer.files.length === 0) return
      
      const file = e.dataTransfer.files[0]
      this.processVideoFile(file)
    },
    
    handleBeforeUnload(e) {
      if (this.uploading) {
        e.preventDefault()
        e.returnValue = '视频正在上传中，确定要离开吗？'
        return e.returnValue
      }
    },

    handleFileSelect(event) {
      const file = event.target.files[0]
      if (!file) return
      
      this.processVideoFile(file)
    },
    
    processVideoFile(file) {
      // 验证文件类型
      const validTypes = ['video/mp4', 'video/quicktime']
      if (!validTypes.includes(file.type)) {
        this.$message.error('请选择MP4或MOV格式的视频文件')
        return
      }

      // 验证文件大小
      if (file.size > 100 * 1024 * 1024) {
        this.$message.error('视频文件大小不能超过100MB')
        return
      }

      // 如果已有视频预览，释放内存
      if (this.videoUrl) {
        URL.revokeObjectURL(this.videoUrl)
      }

      this.videoFile = file
      this.videoUrl = URL.createObjectURL(file)
      
      // 自动生成标题
      if (!this.form.title) {
        // 使用文件名作为标题，去掉扩展名
        const fileName = file.name.replace(/\.[^/.]+$/, "")
        this.form.title = fileName.slice(0, 30) // 限制标题长度
      }
    },

    removeVideo() {
      if (this.videoUrl) {
        URL.revokeObjectURL(this.videoUrl)
      }
      this.videoFile = null
      this.videoUrl = ''
      this.$refs.fileInput.value = ''
    },

    async submitForm() {
      if (!this.canSubmit) {
        this.$message.warning('请完善表单信息')
        return
      }

      try {
        this.uploading = true
        this.uploadProgress = 0

        // 使用API服务上传视频
        await API.publishVideo(
          this.$store.state.token, 
          this.videoFile, 
          this.form.title.trim()
        )

        this.$message.success('视频上传成功!')
        
        // 重置表单
        this.form.title = ''
        this.removeVideo()

        // 跳转到个人中心
        setTimeout(() => {
          this.$router.push('/profile')
        }, 1000)
      } catch (error) {
        console.error('上传失败', error)
        this.$message.error('视频上传失败: ' + (error.response?.data?.status_msg || error.message))
      } finally {
        this.uploading = false
      }
    },

    goToFeed() {
      if (this.uploading) {
        this.$confirm('视频正在上传中，确定要离开吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/feed')
        }).catch(() => {})
        return
      }
      this.$router.push('/feed')
    },
    
    goToPublish() {
      // 当前页面
    },
    goToLog() { this.$router.push('/log') },
    goToProfile() {
      if (this.uploading) {
        this.$confirm('视频正在上传中，确定要离开吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/profile')
        }).catch(() => {})
        return
      }
      this.$router.push('/profile')
    }
  }
}
</script>

<style scoped>
.publish-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;
  color: #fff;
}

.header {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.header h1 {
  font-size: 18px;
  font-weight: 500;
  color: #fff;
}

.back-button {
  font-size: 16px;
  cursor: pointer;
  color: #fff;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(255, 255, 255, 0.1);
}

.upload-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.form-container {
  max-width: 500px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 25px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}

.input-field {
  width: 100%;
  padding: 15px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  color: #fff;
  font-size: 16px;
  transition: all 0.3s ease;
}

.input-field:focus {
  outline: none;
  border-color: #ff2d92;
  box-shadow: 0 0 10px rgba(255, 45, 146, 0.3);
  background: rgba(255, 255, 255, 0.15);
}

.input-field::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.input-counter {
  position: absolute;
  right: 10px;
  bottom: -20px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.upload-wrapper {
  width: 100%;
}

.video-preview-container {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
}

.video-preview {
  width: 100%;
  max-height: 300px;
  border-radius: 12px;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  transition: all 0.3s ease;
}

.remove-btn:hover {
  background: rgba(255, 0, 0, 0.7);
}

.upload-placeholder {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2px dashed rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.05);
  padding: 20px;
}

.upload-placeholder:hover {
  border-color: #ff2d92;
  background: rgba(255, 255, 255, 0.1);
  transform: translateY(-2px);
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.upload-tip {
  font-size: 16px;
  margin-bottom: 5px;
  color: #fff;
}

.upload-desc {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 10px;
}

.upload-drag-tip {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  padding: 5px 15px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.1);
  margin-top: 10px;
}

.submit-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(135deg, #ff2d92, #ff6b35);
  color: #fff;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(255, 45, 146, 0.4);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.loading-spinner {
  animation: spin 1s linear infinite;
}

.upload-progress {
  padding: 20px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  z-index: 10;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #ff2d92, #ff6b35);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #fff;
}

.progress-tip {
  text-align: center;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.tips {
  margin-top: 30px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  border-left: 3px solid rgba(255, 255, 255, 0.3);
}

.tip-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 10px;
  color: rgba(255, 255, 255, 0.9);
}

.tip-list {
  padding-left: 20px;
  margin: 0;
}

.tip-list li {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 5px;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(20px);
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 100;
  max-width: 375px;
  margin: 0 auto;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.3s ease;
  padding: 6px 12px;
  min-width: 60px;
  text-align: center;
}

.nav-item:hover {
  color: white;
  transform: translateY(-1px);
}

.nav-item.active {
  color: #ff2d55;
}

.nav-icon {
  font-size: 18px;
  margin-bottom: 3px;
  line-height: 1;
}

.nav-text {
  font-size: 10px;
  font-weight: 500;
  line-height: 1;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* 移动端适配 */
@media (max-width: 480px) {
  .upload-area {
    padding: 15px;
  }

  .upload-placeholder {
    height: 150px;
  }

  .upload-icon {
    font-size: 36px;
    margin-bottom: 10px;
  }
  
  .upload-tip {
    font-size: 14px;
  }
  
  .upload-desc,
  .upload-drag-tip {
    font-size: 11px;
  }

  .bottom-nav {
    height: 50px;
    padding: 0 5px;
  }

  .nav-item {
    padding: 4px 6px;
    min-width: 45px;
  }

  .nav-icon {
    font-size: 16px;
    margin-bottom: 2px;
  }

  .nav-text {
    font-size: 9px;
  }
}
</style>